<template>
  <div class="app-container">
    <el-card>
      <div style="font-weight:600;margin-bottom:12px;">申请访问权限</div>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="92px">
        <el-form-item label="资源类型" prop="resource_type">
          <el-select v-model="form.resource_type" placeholder="请选择" style="width:100%">
            <el-option label="数据（表/文件）" value="data"/>
            <el-option label="设备" value="device"/>
          </el-select>
        </el-form-item>

        <el-form-item label="资源ID" prop="resource_id">
          <el-input v-model="form.resource_id" placeholder="资源 ID"/>
        </el-form-item>

        <el-form-item label="操作" prop="action">
          <el-select v-model="form.action" placeholder="操作" style="width:100%">
            <el-option label="读" value="read"/>
            <el-option label="写" value="write"/>
          </el-select>
        </el-form-item>

        <el-form-item label="用途">
          <el-input
            type="textarea"
            :rows="3"
            v-model="form.reason"
            placeholder="说明用途（可选）"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="loading" @click="submit">提 交</el-button>
          <el-button @click="resetForm">重 置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'RequestPermission',
  data () {
    return {
      loading: false,
      form: {
        resource_type: 'data',
        resource_id: '',
        action: 'read',
        reason: ''
      },
      rules: {
        resource_type: [{ required: true, message: '请选择资源类型', trigger: 'change' }],
        resource_id: [
          { required: true, message: '请填写资源ID', trigger: 'blur' },
          { validator: (_r, v, cb) => {
              if (v === '' || v === null || v === undefined) return cb()
              const asNum = Number(v)
              if (!Number.isNaN(asNum) && asNum < 0) return cb(new Error('资源ID不能为负数'))
              cb()
            }, trigger: 'blur'
          }
        ],
        action: [{ required: true, message: '请选择操作', trigger: 'change' }]
      }
    }
  },
  methods: {
    resetForm() {
      this.$refs.formRef.resetFields()
      this.form = { resource_type: 'data', resource_id: '', action: 'read', reason: '' }
    },
    normalizePayload() {
      const type = (this.form.resource_type || '').toLowerCase()
      const normalizedType = ['device', 'data'].includes(type) ? type : 'data'
      const ridNum = Number(this.form.resource_id)
      const resource_id = Number.isNaN(ridNum) ? this.form.resource_id : ridNum
      const payload = {
        resource_type: normalizedType,
        resource_id,
        action: this.form.action
      }
      if (this.form.reason && this.form.reason.trim()) {
        payload.remark = this.form.reason.trim()
      }
      return payload
    },
    async submit() {
      this.$refs.formRef.validate(async ok => {
        if (!ok) return
        this.loading = true
        try {
          const payload = this.normalizePayload()
          const res = await request({
            url: '/access/request/create',
            method: 'post',
            data: payload
          })
          const msg = (res && (res.msg || res.message)) || '申请已提交'
          this.$message.success(msg)
          this.resetForm()
        } catch (e) {
          const msg = e?.response?.data?.msg || e?.msg || e?.message || '网络错误'
          this.$message.error('提交失败：' + msg)
        } finally {
          this.loading = false
        }
      })
    }
  }
}
</script>
